package com.jwthhealth_pub.old.common.download;

import android.content.Intent;
import android.util.Log;

import com.jwthhealth_pub.app.App;
import com.jwthhealth_pub.old.common.Constant;
import com.jwthhealth_pub.old.sportfitness.view.SportCourseInfoActivity;
import com.jwthhealth_pub.utils.UnitUtil;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by liuzhen000 on 2017/1/3.
 */

public class DownLoadTask extends Thread {

    private String mUrl = "";
    private String path = "";
    private String fileName = "";

    public DownLoadTask(String _url, String path, String fileName) {
        this.mUrl = _url;
        this.path = path;
        this.fileName = fileName;
    }

    @Override
    public void run() {
        HttpURLConnection httpURLConnection = null;
        RandomAccessFile raf = null;
        InputStream is = null;

        double end = 0;
        double finish = 0l;

        try {
            URL url = new URL(mUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(15000);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setRequestProperty("Accept-Encoding", "identity"); //加上这句话解决问题

            File file = new File(path, fileName);
            raf = new RandomAccessFile(file, "rwd");
            if (httpURLConnection.getResponseCode() == 200) {
                end = httpURLConnection.getContentLength();
                long time = System.currentTimeMillis();
                
                is = httpURLConnection.getInputStream();
                byte buf[] = new byte[1024 * 4];
                int len = -1;
                while ((len = is.read(buf)) != -1){
                    raf.write(buf, 0, len);
                    finish += len;

                    if (System.currentTimeMillis() - time > 500){
                        // TODO: 2017/1/4 发送广播
                        Intent intent = new Intent();
                        intent.setAction(Constant.DOWNLOAD);
                        time = System.currentTimeMillis();
                        String element = UnitUtil.humanReadableByteCount((long)finish, false);
                        Log.d("DownLoadTask", "end:" + end);
                        String denominatior = UnitUtil.humanReadableByteCount((long)end, false);
//                        Log.d("DownLoadTask", denominatior);
                        double _percent = finish / end;
                        int percent = (int) (_percent * 100);
//                        Log.d("DownLoadTask", "percent:" + percent);
//                        String longPrecent = Integer.parseInt(finish) / Integer.parseInt(end);
                        String precent =  element + "/" + denominatior;
                        Log.d("DownLoadTask", "% " + precent);
                        intent.putExtra(Constant.BROADCAST_DOWNLOAD_TYPE, SportCourseInfoActivity.downLoading);
                        intent.putExtra(Constant.BROADCAST_DOWNLOAD_PERCENT, precent);
                        intent.putExtra(Constant.BROADCAST_DOWNLOAD_LONG_PERCENT, percent);
                        App.mContext.sendBroadcast(intent);
                        Log.d("DownLoadTask", percent + "");
                    }
                }

                Log.d("DownLoadTask", "下载完毕");
                Intent intent = new Intent();
                intent.setAction(Constant.DOWNLOAD);
                intent.putExtra(Constant.BROADCAST_DOWNLOAD_TYPE, SportCourseInfoActivity.donwLoadFinish);
                App.mContext.sendBroadcast(intent);

                Log.d("DownLoadTask", file.getPath());
            }
            

        } catch (Exception e) {
            Log.d("DownLoadTask", e.toString());
            Intent intent = new Intent();
            intent.setAction(Constant.DOWNLOAD);
            intent.putExtra(Constant.BROADCAST_DOWNLOAD_TYPE, SportCourseInfoActivity.donwLoadError);
            App.mContext.sendBroadcast(intent);
        } finally {
            try{
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
                if (raf != null) {
                    raf.close();
                }
                if (is != null) {
                    is.close();
                }
            }catch (Exception e) {
                Log.d("DownLoadTask", e.toString());
            }
        }
    }
}
